//
//  KKUserInfoController.m
//  DoMi
//
//  Created by 康凯 on 2016/11/10.
//  Copyright © 2016年 kk. All rights reserved.
//

#import "KKUserInfoController.h"
#import "KKMyHttp.h"
#import "KKUserInfoDetailM.h"
#import "KKUploadDialog.h"
#import <AliyunOSSiOS/OSSService.h>
#import "KKApi.h"
#import "KKJobItemDialog.h"
#import "KKApplyExpertProtocolVC.h"

@interface KKUserInfoController ()<UITextFieldDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (nonatomic,strong)KKUserInfoDetailM *userDetail;
@property (weak, nonatomic) IBOutlet UIView *avatarView;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (strong, nonatomic) OSSClient *client;
@property (strong,nonatomic)NSArray *jobItems;
@property (strong,nonatomic)NSArray *industryItems;
@property (copy,nonatomic)NSString *avatarUrl;
@end

@implementation KKUserInfoController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNav];
    [self initView];
    [self getUserInfoDetail];
    [self getJobItem];
    [self getIndustry];
}

#pragma mark ---初始化nav

-(void)initNav{
    //禁止透明
    self.navigationController.navigationBar.translucent=NO;
    //电量颜色设置
    [UIApplication sharedApplication].statusBarStyle=UIStatusBarStyleLightContent;
    //背景颜色
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithHexString:@"#1B1B1C"];
    //标题字体颜色
    self.navigationController.navigationBar.titleTextAttributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName, nil];
    //返回字体颜色
    self.navigationController.navigationBar.tintColor=[UIColor whiteColor];
    
    self.navigationItem.title=@"完善个人资料";
    self.address.delegate=self;
    self.phone.delegate=self;
}
-(void)initView{
    UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(uploadClick)];
    [self.avatarView addGestureRecognizer:tap];
    UITapGestureRecognizer *tap1=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(jobClick)];
    [self.jobView addGestureRecognizer:tap1];
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker=imagePicker;
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
    
    id<OSSCredentialProvider> credential=[[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey:ACCESSKEY secretKey:SECRETKEY];
    OSSClientConfiguration * conf = [OSSClientConfiguration new];
    conf.maxRetryCount = 2;
    conf.timeoutIntervalForRequest = 30;
    conf.timeoutIntervalForResource = 24 * 60 * 60;
    self.client=[[OSSClient alloc] initWithEndpoint:ENDPOINT credentialProvider:credential clientConfiguration:conf];
}

#pragma mark 初始化数据
-(void)initData{
    //头像
    [self.avatar sd_setImageWithURL:[NSURL URLWithString:self.userDetail.avatar] placeholderImage:[UIImage imageNamed:@"default_avater"]];
    //昵称
    if([KKAppUtils isEmptyString:self.userDetail.nickname]){
        NSString *nickName=[self.userDetail.phone substringFromIndex:self.userDetail.phone.length-4];
        self.nickName.text=nickName;
    }else{
        self.nickName.text=self.userDetail.nickname;
    }
    //真实姓名
    self.realName.text=self.userDetail.realname;
    if(![KKAppUtils isEmptyString:self.userDetail.job]){
        self.job.hidden=NO;
        self.job.text=self.userDetail.job;
    }
    self.company.text=self.userDetail.company;
    self.address.text=self.userDetail.zone;
    self.industray.text=self.userDetail.industry;
    self.phone.text=self.userDetail.phone;
    self.avatarUrl=self.userDetail.avatar;
}

#pragma mark 判断更新数据
-(BOOL)judgeData{
    if([self isEmptyString:self.nickName.text]){
        [self toast:@"请填写昵称"];
        return YES;
    }
    if([self isEmptyString:self.realName.text]){
        [self toast:@"请填写真实姓名"];
        return YES;
    }
    if([self isEmptyString:self.job.text]){
        [self toast:@"请选择职位"];
        return YES;
    }
    if([self isEmptyString:self.company.text]){
        [self toast:@"请填写公司"];
        return YES;
    }
    if([self isEmptyString:self.address.text]){
        [self toast:@"请填写地址"];
        return YES;
    }
    if([self isEmptyString:self.industray.text]){
        [self toast:@"请填写行业"];
        return YES;
    }
    if([self isEmptyString:self.phone.text]){
        [self toast:@"请填写手机号"];
        return YES;
    }
    return NO;
}
#pragma mark 完成按钮
- (IBAction)saveInfoClick:(id)sender {
    [self updateUserInfo];
}
#pragma mark 按钮--职位item
-(void)jobClick{
    KKJobItemDialog *job=[[[NSBundle mainBundle] loadNibNamed:@"KKJobItemDialog" owner:self options:nil] lastObject];
    job.selectItemBlock=^(NSString *title){
        self.job.text=title;
        self.job.hidden=NO;
    };
    job.type.text=@"职位";
    job.items=self.jobItems;
    [job show];
}
#pragma mark 按钮--头像上传
-(void)uploadClick{
    KKUploadDialog *upload=[[[NSBundle mainBundle] loadNibNamed:@"KKUploadDialog" owner:self options:nil] lastObject];
    upload.uploadBlock=^(int flag){
        if(flag==1){
            self.imagePicker.sourceType=UIImagePickerControllerSourceTypeCamera;
        }else if(flag==2){
            self.imagePicker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
        }
        [self presentViewController:self.imagePicker animated:YES completion:nil];
    };
    [upload show];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

#pragma mark imagepicker代理
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    NSString *mediaType=[info objectForKey:UIImagePickerControllerMediaType];
    if ([mediaType isEqualToString:@"public.image"]){
        //如果是图片
        UIImage *selectImg= info[UIImagePickerControllerEditedImage];;
        //压缩图片
        NSData *fileData = UIImageJPEGRepresentation(selectImg, 1.0);
        //保存图片至相册
//        UIImageWriteToSavedPhotosAlbum(selectImg, self,nil, NULL);
        [self uploadObjectAsync:fileData];
        [self.avatar setImage:selectImg];
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark textfiled代理
//在UITextField 编辑之前调用方法
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}
//在UITextField 编辑完成调用方法
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}

#pragma mark 接口--oss上传图片
// 异步上传
- (void)uploadObjectAsync:(NSData *)uploadImgData{
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    NSDate *date = [NSDate date];
    NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
    [fmt setDateFormat:@"yyyy-MM-dd_HH:mm:ss"];
    NSString *ds = [fmt stringFromDate:date];
    
    put.bucketName = BUCKET_NAME;
    put.objectKey = [NSString stringWithFormat:@"%@.jpg",ds];
    put.uploadingData=uploadImgData;
    
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//    hud.mode = MBProgressHUDModeDeterminate;
//    hud.label.text = @"正在上传图片";
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        dispatch_sync(dispatch_get_main_queue(), ^{//其实这个也是在子线程中执行的，只是把它放到了主线程的队列中
            Boolean isMain = [NSThread isMainThread];
            if (isMain) {
                [SVProgressHUD showProgress:totalByteSent/totalBytesExpectedToSend status:@"正在上传图片"];
            
//                float progress = 0.0f;
//                progress=totalByteSent/totalBytesExpectedToSend;
//                [MBProgressHUD HUDForView:self.view].progress = progress;
//                if(progress==1.0f){
//                    [hud hideAnimated:YES];
//                }
                
            }
        });
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    OSSTask * putTask = [self.client putObject:put];
    [putTask continueWithBlock:^id(OSSTask *task) {
        NSLog(@"objectKey: %@", put.objectKey);
        if (!task.error) {
            NSString *url=[NSString stringWithFormat:@"https://%@.%@/%@.jpg?x-oss-process=image/resize,w_600",BUCKET_NAME,@"oss-cn-beijing.aliyuncs.com",ds];
            self.avatarUrl=url;
            [SVProgressHUD dismiss];
            NSLog(@"upload object success!");
        } else {
            NSLog(@"upload object failed, error: %@" , task.error);
        }
        return nil;
    }];
}
#pragma mark 接口--完善信息
-(void)getUserInfoDetail{
    [self showDialog];
    [KKMyHttp getFinishInfoSuccess:^(id data) {
        self.userDetail=data;
        [self initData];
        [self dismissDialog];
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

#pragma mark 接口--职位列表
-(void)getJobItem{
    [KKMyHttp getJobItemSuccess:^(id data) {
        self.jobItems=data;
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 接口--行业列表
-(void)getIndustry{
    [KKMyHttp getIndustryItemSuccess:^(id data) {
        self.industryItems=data;
    } failure:^(NSError *error) {
        
    }];
}

#pragma mark 接口--更新完善信息
-(void)updateUserInfo{
    if([self judgeData]){
        return;
    }
    [self showDialog];
    NSDictionary *params=@{UID_KEY:UID,TOKEN_KEY:TOKEN,
                           @"avatar":self.avatarUrl,@"nickname":self.nickName.text,
                           @"realname":self.realName.text,@"company":self.company.text,
                           @"job":self.job.text,@"zone":self.address.text,
                           @"industry":self.industray.text,@"phone":self.phone.text,};
    [KKMyHttp updateUserInfo:params success:^(id data) {
        [self dismissDialog];
        [self toast:@"保存成功"];
        [self.navigationController popViewControllerAnimated:YES];
        if(self.flag==1){
            KKApplyExpertProtocolVC *protocol=[[KKApplyExpertProtocolVC alloc] init];
            [self.navigationController pushViewController:protocol animated:YES];
        }
    } failure:^(NSError *error) {
        [self dismissDialog];
    }];
}

@end
